import request from '@/utils/request'
import CryptoJS from 'crypto-js'

async function addTemplate({ templates }) {
  const params = {
    template: JSON.stringify(templates),
    sessionid: window.userSessionid || 'qqq',
    timestamp: new Date().getTime()
  }
  return request(window.unreUrl + '/BIM/addTemplate', {
    method: 'POST',
    data: generateParamData(params),
    credentials: 'omit'
  })
}

// eslint-disable-next-line no-unused-vars
async function addTask({ templateId }) {
  const params = {
    templateId: JSON.stringify(1069),
    sessionid: window.userSessionid || 'qqq',
    timestamp: new Date().getTime()
  }
  return request(window.unreUrl + '/BIM/addTask', {
    method: 'POST',
    data: generateParamData(params),
    credentials: 'omit'
  })
}

// token密钥
const API_TOKEN_SEED = 'fqw9me17P0uuhNKPyDiJMxB46vMe6Jg5'
// 排序生成表单数据
const generateParamData = params => {
  const formData = new FormData()
  // 对象的遍历 就已排序
  const keys = Object.keys(params).sort()
  for (const ik of keys) {
    formData.append(ik, params[ik])
  }
  // 添加 token
  formData.append('token', generateToken(params))
  return formData
}

// 生成TOKEN
const generateToken = params => {
  let s = ''
  const keys = Object.keys(params).sort()
  for (const ik of keys) {
    s += params[ik]
  }
  s += API_TOKEN_SEED
  // console.log('service token ', s);
  s = CryptoJS.MD5(s).toString()
  return s
}

const unre = {
  addTask,
  addTemplate
}

export default unre
